package com.ruoyi.comparison.controller;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.utils.BeanCopyUtils;
import com.ruoyi.comparison.domain.*;
import com.ruoyi.comparison.domain.bo.TaskRelationListBo;
import com.ruoyi.comparison.domain.bo.TaskSubjectListBo;
import com.ruoyi.comparison.domain.vo.TaskRelationListVo;
import com.ruoyi.comparison.domain.vo.TaskSubjectListVo;
import com.ruoyi.comparison.service.ITaskRelationListService;
import com.ruoyi.comparison.service.ITaskSubjectListService;
import com.ruoyi.comparison.utils.HttpHelper;
import com.ruoyi.comparison.utils.QiChaChaUtil;
import lombok.RequiredArgsConstructor;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.apache.commons.collections4.list.TreeList;
import org.apache.http.client.methods.HttpHead;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 同一条关联关系上的节点信息
 *
 * @author ruoyi
 * @date 2023-11-18
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/subjectList")
public class TaskSubjectListController extends BaseController {

    private final ITaskSubjectListService iTaskSubjectListService;
    private final ITaskRelationListService relationListService;

    /**
     * 查询同一条关联关系上的节点信息列表
     */
    @SaCheckPermission("system:subject:list")
    @GetMapping("/list")
    public TableDataInfo<TaskSubjectListVo> list(TaskSubjectListBo bo, PageQuery pageQuery) {
        return iTaskSubjectListService.queryPageList(bo, pageQuery);
    }

//    /**
//     * 查询同一条关联关系上的节点信息列表
//     */
//    @SaCheckPermission("system:subject:list")
//    @GetMapping("/allKey")
//    public R<List<TaskSubjectListVo>> findAllKey() {
//        List<TaskSubjectListVo> list = iTaskSubjectListService.findAllKey();
//        return R.ok(list);
//    }

    @SaCheckPermission("system:subject:list")
    @GetMapping("/listRelationList")
    public TableDataInfo<TaskRelation> listRelationList(TaskRelationListBo bo, PageQuery pageQuery) {
        return relationListService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出同一条关联关系上的节点信息列表
     */
    @SaCheckPermission("system:subject:export")
    @Log(title = "同一条关联关系上的节点信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(TaskSubjectListBo bo, HttpServletResponse response) {
        List<TaskSubjectListVo> list = iTaskSubjectListService.queryList(bo);
        ExcelUtil.exportExcel(list, "同一条关联关系上的节点信息", TaskSubjectListVo.class, response);
    }

    /**
     * 获取同一条关联关系上的节点信息详细信息
     */
    @SaCheckPermission("system:subject:list")
    @GetMapping("/allKey")
    public R<List<TaskSubjectListVo>> getInfo() {
        List<TaskSubjectListVo> allKey = iTaskSubjectListService.findAllKey();
        return R.ok(allKey);
    }
    @SaCheckPermission("system:subject:list")
    @PostMapping("/findKey")
    public R<List<TaskSubjectListVo>> findKey(@RequestBody List<Domains> domains) {
        if (domains.size()<2)
            return R.fail("请输入至少两个公司");
        List<TaskSubjectListVo> list = iTaskSubjectListService.findKey(domains);
        return R.ok(list);
    }
    @Value("${qichacha.key}")
    private String key;
    @Value("${qichacha.secretKey}")
    private String secretKey;

    @SaCheckPermission("system:subject:list")
    @PostMapping("/domain")
    public R getList(@RequestBody List<Domains> domains) {
        if (domains.size()<2)
            return R.fail("请输入至少两个公司");
        int a=1;
        for (int m = 0; m < domains.size()-1; m++) {
            for (int n = a; n < domains.size(); n++) {
                String searchKey1 = domains.get(m).getValue();
                String searchKey2 = domains.get(n).getValue();
                if (searchKey1.equals("undefined")||searchKey2.equals("undefined")){
                    return null;
                }
                String reqInterNme = "https://api.qichacha.com/ECIRelationships/GetInfo";
                try {
                    HttpHead reqHeader = new HttpHead();
                    String[] autherHeader = QiChaChaUtil.RandomAuthentHeader(key, secretKey);
                    reqHeader.setHeader("Token", autherHeader[0]);
                    reqHeader.setHeader("Timespan", autherHeader[1]);
                    String reqUri = reqInterNme.concat("?key=").concat(key).concat("&").concat("searchKey1=").concat(searchKey1).concat("&").concat("searchKey2=").concat(searchKey2);
                    String tokenJson = HttpHelper.httpGet(reqUri, reqHeader.getAllHeaders());
                    // 解析JSON字符串
                    JSONObject jsonObject = new JSONObject(tokenJson);
                    String status = jsonObject.getString("Status");
                    if (ObjectUtil.isEmpty(tokenJson)){
                        throw new EmptyStackException();
                    }
                    if(status.equals("200")){
                        JSONObject result1 = jsonObject.getJSONObject("Result");
                        org.json.JSONArray data = result1.getJSONArray("Data");

                        String subjectId = UUID.randomUUID().toString().replaceAll("-","").substring(0,16);

                        List<TaskSubjectList> list = new TreeList<>();
                        for (int i = 0; i < data.length(); i++) {
                            JSONObject jsonObject1 = data.getJSONObject(i);
                            JSONArray subjectList = jsonObject1.getJSONArray("SubjectList");
                            List<DataSubjectResult> dataResults = com.alibaba.fastjson.JSONArray.parseArray(subjectList.toString(), DataSubjectResult.class);
                            if (ObjectUtil.isEmpty(dataResults))
                                return R.ok("无关联关系");
                            for (DataSubjectResult dataResult : dataResults) {
                                TaskSubjectList subject = BeanCopyUtils.copy(dataResult, TaskSubjectList.class);
                                subject.setSearchKey1(searchKey1);
                                subject.setSearchKey2(searchKey2);
                                subject.setCreateTime(new Date());
                                subject.setSubjectId(subjectId);
                                list.add(subject);
                            }
                        }
                        iTaskSubjectListService.insert(list);
                        List<TaskRelationList> list2 = new TreeList<>();
                        for (int i = 0; i < data.length(); i++) {
                            JSONObject jsonObject1 = data.getJSONObject(i);
                            JSONArray subjectList = jsonObject1.getJSONArray("RelationList");
                            List<DataRelationResult> dataResults = com.alibaba.fastjson.JSONArray.parseArray(subjectList.toString(), DataRelationResult.class);
                            for (int i1 = 0; i1 < dataResults.size(); i1++) {
                                for (int i2 = 0; i2 < dataResults.get(i1).getPropertyList().size(); i2++) {
                                    TaskRelationList relation =new TaskRelationList();
                                    relation.setType(dataResults.get(i1).getPropertyList().get(i2).getType());
                                    relation.setLabelText(dataResults.get(i1).getPropertyList().get(i2).getLabelText());
                                    relation.setStartNodeId(dataResults.get(i1).getStartNodeId());
                                    relation.setEndNodeId(dataResults.get(i1).getEndNodeId());
                                    relation.setSubjectId(subjectId);
                                    list2.add(relation);
                                }
                            }
                        }
                        relationListService.insertBatch(list2);
                    }
                } catch (Exception e1) {
                    e1.printStackTrace();
                    return R.fail("裁判文书查询失败！");
                }
            }
            a++;
        }
        return R.ok();
    }

    /**
     * 删除同一条关联关系上的节点信息
     *
     * @param ids 主键串
     */
    @SaCheckPermission("system:subject:list")
    @Log(title = "同一条关联关系上的节点信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(iTaskSubjectListService.deleteWithValidByIds(Arrays.asList(ids), true));
    }
}
